package net.sunbeta.test.annotation;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.testng.IMethodSelector;
import org.testng.IMethodSelectorContext;
import org.testng.ITestNGMethod;

public class ScheduledTestSelector implements IMethodSelector {

    /**
    * @return true if either of the following conditions is true:
    * - method doesn't have an @ScheduledTest annotation
    * - method has an @ScheduledTest annotation whose activeAfter
    * attribute is equal to a date in the past.
    */
    public boolean includeMethod(IMethodSelectorContext context, ITestNGMethod method, boolean isTestMethod) {

        Method method2 = method.getMethod();
        ScheduledTest annotation = method2.getAnnotation(ScheduledTest.class);
        if (annotation != null) {
            Date now = Calendar.getInstance().getTime();
            Date activeAfter = null;
            String activeAfterString = annotation.activeAfter();
            if (activeAfterString != null && !"".equals(activeAfterString)) {
                activeAfter = parse(activeAfterString);
                // Only include this method if now is after the
                // "activeAfter" date
                if (now.before(activeAfter)) {
                    // We don't want that method
                    return false;
                }
            }
            // else run if no date was specified
        }
        return true;
    }

    @Override
    public void setTestMethods(List<ITestNGMethod> arg0) {
        // TODO Auto-generated method stub

    }

    /**
    * Create a Date representing the format passed in parameter.
    * @param format Must be formatted as "yyyy-mm-dd hh:mm"
     * @throws ParseException 
    */
    private Date parse(String dateString) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return formatter.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
